#include "snowboy-detect-c-wrapper.h"
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include "record.h"

// 定义录音时间的阈值（以秒为单位）
#define SILENCE_THRESHOLD 5

int main()
{
    // 创建 snowboy 检测器
    SnowboyDetect* detector = SnowboyDetectConstructor("common.res", "tianle.pmdl");
    if (!detector)
    {
        return EXIT_FAILURE;
    }

    // 设置灵敏度
    SnowboyDetectSetSensitivity(detector, "0.5");

    // 获取检测器支持的音频数据参数
    // 采样深度
    int bits = SnowboyDetectBitsPerSample(detector);
    // 声道数量
    int channels = SnowboyDetectNumChannels(detector);
    // 采样频率
    int rate = SnowboyDetectSampleRate(detector);

    printf("采样深度: %d\n", bits);
    printf("声道数量: %d\n", channels);
    printf("采样频率: %d\n", rate);

    // 初始化音频录制上下文
    audio_record_context_t *context = audio_record_init("hw:0,1", channels, rate, "output.pcm");
    if (!context)
    {
        return EXIT_FAILURE;
    }

    char *buffer = malloc(snd_pcm_frames_to_bytes(context->pcm_handle, context->period_size)); // 分配缓冲区
    if (!buffer) {
        perror("malloc");
        audio_record_stop(context);
        SnowboyDetectDestructor(detector);
        return EXIT_FAILURE;
    }

    time_t last_sound_time = 0;
    int recording = 0;

    while (1)
    {
        snd_pcm_sframes_t frames = snd_pcm_readi(context->pcm_handle, buffer, context->period_size); // 从PCM设备读取数据
        if (frames < 0)
        {
            fprintf(stderr, "Error from read: %s\n", snd_strerror(frames));
            snd_pcm_recover(context->pcm_handle, frames, 0);
            continue;
        }

        // 检测音频数据中的唤醒词
        int status = SnowboyDetectRunDetection(detector, (int16_t*)buffer, snd_pcm_frames_to_bytes(context->pcm_handle, frames) / sizeof(int16_t), 0);
        if (status > 0)
        {
            printf("检测到唤醒词\n");
            if (!recording)
            {
                recording = 1;
                audio_record_reinit(context, "hw:0,1", channels, rate, "output.pcm");
                audio_record_start(context);
                last_sound_time = time(NULL);
                printf("开始录音\n");
            }
        }

        // 检测音频数据中的声音活动
        if (status == 0)
        {
            last_sound_time = time(NULL);
        }

        // 检查是否超过阈值时间
        if (recording && difftime(time(NULL), last_sound_time) >= SILENCE_THRESHOLD)
        {
            printf("检测到静音，停止录音\n");
            audio_record_stop(context);
            recording = 0;
        }
    }

    free(buffer);
    audio_record_cleanup(context);
    SnowboyDetectDestructor(detector);

    return EXIT_SUCCESS;
}
